# coding=UTF-8
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login as do_login, logout as do_logout
from django.contrib.auth.models import User
from djopping_user.forms import LoginForm, SignupForm, PasswordReminderUserForm, PasswordReminderEmailForm, SetPasswordForm, InputRegistrationKeyForm
from djopping_user.utils import keygen, send_registration_key
from djopping_user.models import Registration
from djopping_user.exceptions import DatabaseError, SendRegistrationKeyError, SaveUserError, SaveRegistrationError
from decorators import render_response
to_response=render_response('djopping/user/')

@to_response
def login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    errors = []
    login_form = LoginForm()
    if request.POST:
        post = request.POST.copy()
        login_form = LoginForm(post)
        if login_form.is_valid():
            user = authenticate(username=post.get('username', None), password=post.get('password', None))
            if user is not None:
                if user.is_active:
                    do_login(request, user)
                    if user.password == '':
                        return set_registration_password(request)
                    else:
                        return HttpResponseRedirect(request.POST.get('next', '/'))
                else:
                    errors.append(_(u'Su usuario no se encuentra activo.'))
            else:
                errors.append(_(u'Usuario y/o contraseña incorrectos.'))
    else:
        return 'login_form.html', { 'login_form': login_form, 'next_': request.POST.get('next', '/') }
    return 'error.html', { 'errors': errors, 'login_form_errors': login_form.errors, 'next_': request.POST.get('next', '/') }

@to_response
def logout(request):
    do_logout(request)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

@to_response
def signup(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    signup_form = SignupForm()
    referer = None
    errors = []
    if request.method == 'POST':
        post = request.POST.copy()
        referer = post.get('next', None)
        signup_form = SignupForm(post)
        if signup_form.is_valid():
            try:
                start_registration(post)
            except DatabaseError, e:
                errors.append(_(u'Ocurrió un error grave al guardar los datos, vamos a tener que pedirle que los vuelva a ingresar. Es poco común que suceda, los administradores del sitio ya fueron informados y se pondrán a trabajar en el problema.'))
                return 'registration_error.html', { 'errors': errors, 'back': request.GET.get('next', None) }
            except SendRegistrationKeyError, e:
                #TODO: do something?
                pass
            return HttpResponseRedirect('/user/registro/0k/?next=' + post.get('next', '/'))
    return 'signup.html', { 'signup_form': signup_form, 'referer_': referer }

@to_response
def signup_ok(request):
    return 'signup_ok.html', { 'back': request.GET.get('next', None) }

@to_response
def complete_registration(request, key=None):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    errors = []
    if key is not None:
        try:
            registration = Registration.objects.get(key=key, completed=False)
        except DoesNotExist, e:
            raise Http404
        try:
            finish_registration(registration)
        except SaveUserError, e:
            errors.append(_(u'Hubo un error procesando el registro, por favor vuelva al correo que le enviamos y haga click nuevamente en el vínculo.'))
        except SaveRegistrationError, e:
            errors.append(_(u'Hubo un error procesando el registro, por favor vuelva al correo que le enviamos y haga click nuevamente en el vínculo.'))
    else:
        input_key_form = InputRegistrationKeyForm()
        if request.method == 'POST':
            post = request.POST.copy()
            input_key_form = InputRegistrationKeyForm(post)
            if input_key_form.is_valid():
                return HttpResponseRedirect('/user/registro/' + post['key'])
        return 'input_key.html', { 'input_key_form': input_key_form }
    if errors:
        return 'registration_error.html', { 'errors': errors, 'back': request.GET.get('next', None) }
    else:
        return set_registration_password(request, registration)

#TODO: Cron que borre los registros mayores a 1 semana.
@to_response
def set_registration_password(request, registration=None):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    set_password_form = SetPasswordForm()
    if request.method == 'POST':
        post = request.POST.copy()
        set_password_form = SetPasswordForm(post)
        try:
            registration = Registration.objects.get(user=User.objects.get(id=post['user_id']), key=post['registration_key'])
        except Registration.DoesNotExist:
            return HttpResponseRedirect('/')
        if set_password_form.is_valid():
            user = registration.user
            if user.password == '':
                user.set_password(post['password1'])
                user.save()
                #FIXME: Este hijo de mil putas no matchea. Si le paso urlconf='djopping_user.urls' encuentra la URL y redirecciona, pero dsps no matchea la vista. Si no le paso nada me tira un NoReverseMatch.
                #return HttpResponseRedirect(reverse('registration_successful'))
                return HttpResponseRedirect('/user/registro/exitoso/')
            else:
                return HttpResponseRedirect('/')
    if registration:
        params = { 'user_id': registration.user.id, 'registration_key': registration.key, 'set_password_form': set_password_form }
    else:
        return HttpResponseRedirect('/')
    return 'set_password.html', params

@to_response
def registration_successful(request):
    return 'registration_successful.html'

def start_registration(post):
    user = User(
        username=post['username'],
        email=post['email'],
        first_name=post['first_name'],
        last_name=post['last_name'],
        is_active=False
    )
    registration = Registration(user=user, key=keygen(user))
    try:
        user.save()
        registration.user=user
        registration.save()
    except Exception, e:
        print e
        if user.id:
            user.delete()
        if registration.id:
            registration.delete()
        raise DatabaseError(e)
    try:
        send_registration_key(user)
    except Exception, e:
        print e
        raise SendRegistrationKeyError(e)
    return True

def finish_registration(registration):
    user = registration.user
    user.is_active=True
    registration.completed=True
    try:
        user.save()
    except Exception, e:
        raise SaveUserError(e)
    try:
        registration.save()
    except Exception, e:
        user.is_active=False
        user.save()
        raise SaveRegistrationError(e)
    return True

@to_response
def remind(self):
    remind_user = PasswordReminderUserForm()
    remind_email = PasswordReminderEmailForm()
    return 'remind.html', { 'remind_user': remind_user, 'remind_email': remind_email }

